package server.factory;

import annotation.RpcService;
import config.RpcConfig;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author David
 */
@Slf4j
public class ServicesFactory {

    static Map<String, Object> map = new ConcurrentHashMap<>();

    static {

        try {
            String packageName = RpcConfig.getPackageName();
            Reflections f = new Reflections(packageName);
            Set<Class<?>> serviceSet = f.getTypesAnnotatedWith(RpcService.class);

            for (Class<?> c : serviceSet) {

                // 循环获取标记的注解
                Class<?> instanceClass = Class.forName(c.getName());
                String name = c.getInterfaces()[0].toString();
                int i = name.length() - 1;
                while(name.charAt(i) != '.'){
                    i --;
                }
                // 将类的实例存入哈希表，根据接口的类的名称找到具体的实例
                map.put(name.substring(i+1), instanceClass.newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static <T> T getService(String interfaceClass) {
        return (T) map.get(interfaceClass);
    }
}
